//userController
const userService  = require('../../services/admin/userService')
const sendMsg = require("../../tools/sendMsg"); //引入数据库封装模块
const tokenTools = require("../../tools/token"); //引入数据库封装模块
const allTools = require("../../tools/allTools"); //引入数据库封装模块
const db = require("../../config/environment.json"); //引入数据库封装模块
var jwt = require('jsonwebtoken');
const SECRET_KEY = db.JWT_SECRET || 'TEST';

const userController = {
    searchUser: async (req,res)=>{
        const result = await userService.searchUser(req.body)
        sendMsg.checkResult(res, result, 4)
    },
    addUser: async (req,res)=>{
        const result = await userService.addUser(req.body)
        sendMsg.checkResult(res, result, 1)
    },
    delUser: async (req,res)=>{
        const result = await userService.delUser(req.body)
        sendMsg.checkResult(res, result, 2)
    },
    updateUser: async (req,res)=>{
        const result = await userService.updateUser(req.body)
        sendMsg.checkResult(res, result, 3)
    },
    loginChecked: async (req,res)=>{
        const result = await userService.loginChecked(req.body)

        // 处理查询结果
        const data = result.map(row => {
        // 将Rowdatapacket对象转换为普通对象
            return { ...row };
        });

        let msg = ''
        const REFRESH_TOKEN_EXPIRES_IN_MS = db.REFRESH_TOKEN_EXPIRES_IN_MS || 24 * 60 * 60 // 示例值，设置为24小时（可自定义）
        if(data.length > 0){
            const accessToken = tokenTools.generateAccessToken(data[0].id)
            const refreshToken = tokenTools.generateRefreshToken(data[0].id)

            data[0].accessToken = accessToken
            data[0].refreshToken = refreshToken

            data[0].expiresAt = new Date(Date.now() + REFRESH_TOKEN_EXPIRES_IN_MS + db.gobal_time)
            console.log(data[0].expiresAt)

            const decoded = jwt.verify(refreshToken, SECRET_KEY);
            console.log(decoded)

            // return
            const result02 = await userService.saveRefreshToken(data[0])
            msg = '登录成功'
        }else {
            msg = '用户名或密码错误'
        }

        sendMsg.checkResult(res, data, 4, msg)
    },
    updateUserInfo: async (req,res)=>{
        const result = await userService.updateUserInfo(req.body)
        sendMsg.checkResult(res, result, 3)
    },



    refresh: async (req,res)=>{
        const { refreshToken } = req.body;
        console.log(refreshToken)
        try {
            const decoded = jwt.verify(refreshToken, SECRET_KEY);
            console.log(decoded)
            if (!decoded.purpose || decoded.purpose !== 'refresh') {
                throw new Error('令牌用途无效');
            }
        
            // 查询数据库中是否存在有效的 Refresh Token
            console.log(new Date())
            const storedRefreshToken = await userService.findRefreshToken({ token: refreshToken, expiresAt: new Date() });
            const dataList = allTools.getJson(storedRefreshToken)
            console.log(dataList)
            console.log(123456)
            if (dataList.length === 0) {
                throw new Error('无效的验证码');
            }
        

            let a = null
            let b = null
            let c = null
            let d = null
            if(dataList && dataList[0]){
                a = dataList[0].expiresAt
                b = new Date(Date.now() + db.gobal_time)
                c = new Date(dataList[0].expiresAt).getTime()
                d = Date.now() 
            }
            // console.log('---------------')
            // console.log(a)
            // console.log(b)
            // console.log(c)
            // console.log(d)
            // console.log('--------------')

            // 如果 Refresh Token 仍然有效，则：
            if (c > d) {
                // 仅生成新的 Access Token
                const accessToken = jwt.sign({ userId: decoded.userId }, SECRET_KEY, { expiresIn: '2s' });
                // 返回新的 Access Token
                res.json({ success: '成功', accessToken });
            
                // 可选：如果存在定期更换 Refresh Token 的策略，在此处生成和存储新的 Refresh Token
                // （这里假设不自动更换已有效的 Refresh Token）
            } else {
                // Refresh Token 已经失效
                // 删除数据库中过期的 Refresh Token（即使已经过期，也应该删除以保持数据一致性）
                await userService.delRefreshToken(dataList[0]);
            
                // 抛出错误，提示客户端 Refresh Token 已过期，需要重新登录
                throw new Error('刷新令牌已过期，请重新验证。');
            }
        } catch (error) {
            console.log(error)
            res.status(401).json({ message: '刷新令牌失败' });
        }
    },
}

module.exports = userController
